package com.lagou.threadpool;

import com.lagou.data.DataListUtil;
import com.lagou.data.MethodBeanInfo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Stream;

public class WachingThreadPool extends FixedThreadPool implements Runnable {
    // TP90  TP99
    private static final double TP90 = 0.90;
    private static final double TP99 = 0.99;

    public WachingThreadPool() {
        // 每隔5秒打印线程使用情况
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this, 1, 5, TimeUnit.SECONDS);
    }

    @Override
    public Executor getExecutor(URL url) {
        return super.getExecutor(url);
    }

    @Override
    public void run() {
        Map<String, List<MethodBeanInfo>> stringListMap = DataListUtil.get();
        if (!stringListMap.isEmpty()) {
            Iterator<Map.Entry<String, List<MethodBeanInfo>>> iterator = stringListMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<MethodBeanInfo>> next = iterator.next();
                String key = next.getKey();
                List<MethodBeanInfo> value = next.getValue();
                Stream<MethodBeanInfo> methodBeanInfoStream = value.stream().
                        filter(info -> info.endTimeBetween(System.currentTimeMillis()));
                Optional<MethodBeanInfo> max = methodBeanInfoStream.max(Comparator.comparing(MethodBeanInfo::getTime));
                long time = max.get().getTime();
                System.out.println("方法：" + key + ", TP90：" + (int) (time * TP90) + ",----TP99：" + (int) (time * TP99));
            }
        }
    }
}
